#include "Cache/CacheManager.hh"
#include "Configuration.hh"
#include "Log/Log.hh"
#include "HONG.hh"


using std::unique_lock;

CacheManager* CacheManager::_instance = nullptr;


CacheManager* CacheManager::createCacheManager(){
    if(_instance == nullptr){
        _instance = new CacheManager();
    }
    return _instance;
}


void CacheManager::destoryCacheManager(){
    if(_instance != nullptr){
        delete _instance;
        _instance = nullptr;
    }
}

vector<LRUCache>& CacheManager::getCaches(){
    return _caches;
}


CacheManager::CacheManager()
    : _caches(THREAD_NUM, CACHE_SIZE)
    , _swapCache(THREAD_NUM, CACHE_SIZE)
    , _locks(THREAD_NUM){
    // 文件读入缓存
    auto& conf_map = Configuration::createConfig()->getConfigMap();
    for(size_t i = 0; i < _caches.size(); i++){
        _caches[i].readFromFile(conf_map["cacahe_file"][0]);
    }

    _manager.readFromFile(conf_map["cacahe_file"][0]);

    Log::info("缓存数量: %d, 锁的数量: %d", _caches.size(), _locks.size());
}


set<thread::id>& CacheManager::getPidSet(){
    return _p_id_set;
}


vector<thread::id>& CacheManager::getPidVec(){
    return _p_id_vec;
}


vector<mutex>& CacheManager::getLocks(){
    return _locks;
}

LRUCache& CacheManager::getManager(){
    return _manager;
}

void CacheManager::update(){
    // 交换
    for(size_t i = 0; i < _caches.size(); i++){
        unique_lock<mutex> ul(_locks[i]);
        Log::info("%d 号缓存已被上锁, 正在交换缓存", i);
        swapCache(_caches[i], _swapCache[i]);
    }

    // 第二次交换
    for(size_t i = 0; i < _swapCache.size(); i++){
        _manager.addElement(_swapCache[i]);
    }

    // 同步
    for(size_t i = 0; i < _swapCache.size(); i++){
        _swapCache[i].addElement(_manager);

    }
    Log::info("缓存同步完成");

    // Log::debug("*******%d")
}


// 交换和同步任务
// void CacheManager::update(){
//     for(size_t i = 0; i < _caches.size() - 1; i++){
//         unique_lock<mutex> ul(_locks[i]);
//         Log::debug("%d 号缓存已被上锁, 正在上传缓存", i);

//         auto& pending_list = _caches[i].getPendingList();
//         if(pending_list.size() != 0){
//             for(auto& elem : pending_list){
//                 _caches[_caches.size() - 1].addElement(elem.first, elem.second);
//             }
//             _caches[i].clearPendingList();
//         }

//         Log::debug("%d 号缓存上传完成", i);
//     }

//     for(size_t i = 0; i < _caches.size() - 1; i++){
//         unique_lock<mutex> ul(_locks[i]);
//         Log::debug("%d 号缓存已被上锁, 正在同步缓存", i);
//         _caches[i].update(_caches[_caches.size() - 1]);

//         Log::debug("%d 号缓存同步完成", i);
//     }

//     Log::info("缓存同步完成");
// }